package com.meowcook.controller;

import com.meowcook.config.AppConfig;
import com.meowcook.common.AppResult;
import com.meowcook.common.ResultCode;
import com.meowcook.pojo.vo.UserDetailVO;
import com.meowcook.pojo.vo.UserPartIVO;
import com.meowcook.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-04-28
 * Time: 15:02
 */
@Slf4j
@Api(tags = "用户操作接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;


    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult<String> register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("confirmPassword") @NonNull String confirmPassword) {
        log.info("用户名：" + username, "密码：" + password, "确认密码：" + confirmPassword);
        // 校验用户名是否为纯数字
        if (!username.matches(AppConfig.USERNAME_CHECK)){
            return AppResult.fail(ResultCode.FAIL_USER_PARAM_USERNAME_INVALID);
        }
        // 校验密码是否为数字和字母组成
        if (!password.matches(AppConfig.PASSWORD_CHECK)){
            return AppResult.fail(ResultCode.FAIL_USER_PARAM_PASSWORD_INVALID);
        }
        // 校验两次密码是否一致
        if (!password.equals(confirmPassword)) {
            return AppResult.fail(ResultCode.FAIL_USER_TWO_PWD_NOT_SAME);
        }
        userService.register(username, password);
        return AppResult.success("注册成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult<Byte> login(HttpServletRequest request, HttpServletResponse response,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        log.info("用户名：" + username, "密码：" + password);
        // 调用Service
        UserDetailVO user = userService.login(username, password);
        // 使旧的session失效
        HttpSession oldSession = request.getSession(false);
        if (oldSession != null) oldSession.invalidate();
        // 设置新的session
        HttpSession session = request.getSession(true);
        UserPartIVO userPartIVO = new UserPartIVO();
        userPartIVO.setId(user.getId());
        session.setAttribute(AppConfig.USER_SESSION_KEY,userPartIVO);
        session.setMaxInactiveInterval(60*60*24);
        // 设置cookie存储sessionId，HttpSession存储在服务器端，只需存储sessionId就可以在服务器检索到session信息
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60 * 60 * 24); //设置cookie 和 session生命周期同步.
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setSecure(true);
        response.addCookie(cookie);
        // 返回结果
        return AppResult.success(user.getStatus());
    }

    @ApiOperation("判断用户是否登录")
    @PostMapping("/checkLogin")
    public AppResult checkLogin(HttpServletRequest request) {
        log.info("判断用户是否登录");
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppConfig.USER_SESSION_KEY) != null) {
            return AppResult.success(ResultCode.FAIL_USER_LOGIN.toString());
        }
        return AppResult.fail(ResultCode.FAIL_USER_NOT_LOGIN);
    }

    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        log.info("退出登录");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(AppConfig.USER_SESSION_KEY) == null) {
            return AppResult.fail(ResultCode.FAIL_USER_NOT_LOGIN);
        }
        session.invalidate();
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改用户状态")
    @PostMapping("/updateStatus")
    public AppResult updateStatus(HttpServletRequest request) {
        log.info("修改用户登录状态");
        // 获取用户id
        HttpSession session = request.getSession(false);
        UserPartIVO user = (UserPartIVO) session.getAttribute(AppConfig.USER_SESSION_KEY);
        Long id = user.getId();
        // 封装要更改的用户信息
        UserDetailVO updateUser = new UserDetailVO();
        updateUser.setId(id);
        updateUser.setStatus((byte) 0);
        //调用Service更新用户登录状态
        userService.updateUserLoginStatus(updateUser);
        return AppResult.success();
    }

    @ApiOperation("获取用户部分信息")
    @GetMapping("/getPartUserInfo")
    public AppResult<UserPartIVO> getPartUserInfo(HttpServletRequest request,
                                                  @ApiParam("用户id") @RequestParam(value = "userId", required = false) Long userId) {
        if (userId == null) {
            HttpSession session = request.getSession(false);
            UserPartIVO user = (UserPartIVO) session.getAttribute(AppConfig.USER_SESSION_KEY);
            userId = user.getId();
        }
        log.info("用户id: {}", userId);
        return AppResult.success(userService.getPartUserInfo(userId));
    }

    @ApiOperation("获取个人中心用户信息")
    @GetMapping("/getDetailUserInfo")
    public AppResult<UserDetailVO> getDetailVO(HttpServletRequest request,
                                               @ApiParam("用户id") @RequestParam(value = "userId", required = false) Long userId) {
        // 如果userId为空则表明访问登录用户的个人信息，不为空则访问他人个人信息，要对他人信息做相应的保密
        if (userId == null) {
            HttpSession session = request.getSession(false);
            UserPartIVO user = (UserPartIVO) session.getAttribute(AppConfig.USER_SESSION_KEY);
            userId = user.getId();
            log.info("用户id: {}", userId);
            return AppResult.success(userService.getDetailUserInfo(userId));
        } else {
            log.info("用户id: {}", userId);
            UserDetailVO userInfo = userService.getDetailUserInfo(userId);
            userInfo.setEmail(null);
            userInfo.setPhoneNum(null);
            return AppResult.success(userInfo);
        }
    }

    @ApiOperation("修改密码")
    @PostMapping("/changePassword")
    public AppResult changePassword(HttpServletRequest request,
                                   @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword) {
        UserPartIVO user = (UserPartIVO) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
        userService.changePassword(user.getId(), newPassword);
        return AppResult.success();
    }

    @ApiOperation("修改昵称")
    @PostMapping("/changeNickname")
    public AppResult changeNickname(HttpServletRequest request,
                                   @ApiParam("新昵称") @RequestParam("newNickname") @NonNull String newNickname) {
        UserPartIVO user = (UserPartIVO) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
        userService.changeNickname(user.getId(), newNickname);
        return AppResult.success();
    }
}
